package com.hoshiicloud.elasticsearch.service.impl;


import com.hoshiicloud.elasticsearch.entity.Sku;
import com.hoshiicloud.elasticsearch.mapper.SkuDao;
import com.hoshiicloud.elasticsearch.repository.SkuRepository;
import com.hoshiicloud.elasticsearch.service.SkuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


/**
 * 商品搜索管理Service实现类
 * Created by macro on 2018/6/19.
 */
@Service
public class SkuServiceImpl implements SkuService {
    private static final Logger LOGGER = LoggerFactory.getLogger(SkuServiceImpl.class);

    @Autowired
    private SkuDao skuDao;

    @Autowired
    private SkuRepository skuRepository;

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Override
    public int importSkuAll() {
        List<Sku> skuList = skuDao.getSkuList(null);
        Iterable<Sku> skuIterable = skuRepository.saveAll(skuList);
        Iterator<Sku> iterator = skuIterable.iterator();
        int result = 0;
        while (iterator.hasNext()) {
            result++;
            iterator.next();
        }
        return result;
    }

    @Override
    public void delete(Long id) {
        skuRepository.deleteById(id);
    }

    @Override
    public Sku create(Long id) {
        Sku result = null;
        List<Sku> skuList = skuDao.getSkuList(id);
        if (skuList.size() > 0) {
            Sku sku = skuList.get(0);
            result = skuRepository.save(sku);
        }
        return result;
    }

    @Override
    public void delete(List<Long> ids) {
        if (!CollectionUtils.isEmpty(ids)) {
            List<Sku> skuList = new ArrayList<>();
            for (Long id : ids) {
                Sku sku = new Sku();
                sku.setId(id);
                skuList.add(sku);
            }
            skuRepository.deleteAll(skuList);
        }
    }

    @Override
    public Page<Sku> search(String keyword, Integer pageNum, Integer pageSize) {
        Pageable pageable = PageRequest.of(pageNum, pageSize);
        return skuRepository.findBySkuTitle(keyword, pageable);
    }


}
